<?php
namespace app\apishop\controller;
use Common\Jpush;
use Common\Oss;
use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Cookie;
use think\Controller;
use think\Paginator;
use think\Loader;
use app\apishop\controller\Base;
class Index extends Base
{
    public  function _initialize(){
        //TOKEN验证
        $Re = get_getallheaders();
        return json($Re);
        exit;
//        if(empty($Re['Token'])){
//            $result = Config::get('code.tokenfalse');
//            echo json_encode($Re);
//            exit;
//        }
    }
    public function index()
    {
        // $area = getAreaList();
        // return json($area);
        return 'APISHOP接口模块运行正常!';
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-02-23T14:57:18+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 获取1,2,3级地址树
     * @param:
     * @return [type] [description]
     */
    public function getAreaTree(){
        $Re0 = Db::query("select DISTINCT admin_name1,admin_name2,admin_name3 from v_gb_district where admin_name1  ='England' AND admin_name2  <>'' ORDER BY admin_name2");
        $Re1 = Db::query("select DISTINCT admin_name1,admin_name2,admin_name3 from v_gb_district where admin_name1  ='Northern Ireland'  ORDER BY admin_name2");
        $Re2 = Db::query("select DISTINCT admin_name1,admin_name2,admin_name3 from v_gb_district where admin_name1  ='Scotland'  ORDER BY admin_name2");
        $Re3 = Db::query("select DISTINCT admin_name1,admin_name2,admin_name3 from v_gb_district where admin_name1  ='Wales'  ORDER BY admin_name2");
        $count0 = count($Re0);
        $count1 = count($Re1);
        $count2 = count($Re2);
        $count3 = count($Re3);
        $arr0 = setTree($Re0,$count0);
        $arr1 = setTree($Re1,$count1);
        $arr2 = setTree($Re2,$count2);
        $arr3 = setTree($Re3,$count3);
        $arr = array(
                '0' => array('nameEn' =>'England','name' =>'英格兰','isParent'=>true,'children'=>$arr0),
                '1' => array('nameEn' =>'Northern Ireland','name' =>'北爱尔兰','isParent'=>true,'children'=>$arr1),
                '2' => array('nameEn' =>'Scotland','name' =>'苏格兰','isParent'=>true,'children'=>$arr2),
                '3' => array('nameEn' =>'Wales','name' =>'威尔士','isParent'=>true,'children'=>$arr3)
            );
        return json($arr);
    }
    
    function getAreaListByCode(){
        $post = request()->post();
        $postcode = str_replace(' ','',$post['code']);
        $Re = getAreaInfoByCode($postcode);
        if (!$Re){
            $result = Config::get('code.null');
            return json($result);
        }
        $result = Config::get('code.success');
        $result['list'] = $Re;
        $result['count'] = count($Re);
        return json($result);
    }

    public function getMsgCode(){
        $post = request()->post();
        $tel = $post['tel'];
        $tag = $post['tag'];
        $where['account'] = $tel;
        $Re  = Db::name('supplier')->where($where)->find();
        $Res = Db::name('user')->where($where)->find();
        if($Re || $Res){
            if($tag=='register'){
                if($Re){
                    $result = Config::get('code.regin');
                }else{
                    $result = Config::get('code.regin');
                    $result['msg'] = '手机号已在用户端注册，不能再次注册';
                }
                return json($result);
            }
            $param = codeRange();
            $ret = json_decode(SendMsg($tel,$param),true);
            if($ret['code']=='000000'){
                $result = Config::get('code.success');
                Session::set('telCode_'.$tel,$param);
                Session::set($tel.'start',time());
            }else{
                $result = Config::get('code.error');
            }
        }else{
            if($tag=='register'){
                $param = codeRange();
                $ret = json_decode(SendMsg($tel,$param),true);
                if($ret['code']=='000000'){
                    $result = Config::get('code.success');
                    Session::set('telCode_'.$tel,$param);
                    Session::set($tel.'start',time());
                }else{
                    $result = Config::get('code.codeFail');
                }
            }else{
                $result = Config::get('code.register');
                $result['post'] = $post;
            }
        }
        return json($result);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-01-22T13:50:52+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:初始化 获取基础地理信息 以及 基础数据信息 
     * @param:
     * @return [type] [description]
     */
    public function getDataBase(){
        $area = getAreaList();
        $data = getBase();
        $result['status']   = 200;
        $result['area']     = $area ;
        $result['data']     = $data ;
        return json($result);
    }
    public function getAreaList(){
        $area = getAreaList();
        $result['area'] = $area ;
        return json($area);
    }
    
    public function getAreaListByAdminCode(){
        $code = input('code','','trim');
        if(!in_array($code, ['','ENG','NIR','SCT','WLS'])){
            $res = config('code.mistake');
        }else{
            $list = Db::name('gb_postal_code')->where(['admin_code1'=>$code])->fetchSql()->select();
//            var_dump($list);exit;
        }
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-01-22T13:52:37+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:根据二级地区名称 获取3级地址信息
     * @param:
     * @return[description]
     */
    public function getAreaChild(){
        $post = request()->post();
        $name = $post['name'];
        if(empty($name)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $Re = getAreaListByParent($name);
        if($Re){
            $result = Config::get('code.success');
            $result['list'] = $Re;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-01-15
     * @rewriter:杨建
     * @rewriter_date:2018-01-17
     * @description:刷新商户信息
     * @param:
     * @return[$result]
     */
    public function getUserInfo(){
        $post = request()->post();
        $id = $post['supplier_id'];
        $Re = Db::name('supplier')
                ->alias('A')
                ->field('A.*,S.name as disName,S.id as dis_id,B.message')
                ->join('discount S', 'S.supplier_id = A.id','left')
                ->join('supplier_auth B', 'B.supplier_id = A.id','left')
                ->where('A.id',$id)
                ->order('dis_id desc')
                ->find();
        $Re['currency'] = Db::name('system_setting')->where('name','货币')->value('value');

        if($Re){
            $result = Config::get('code.success');
            $result['info'] = $Re;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    
    /********************************************/
    //用户注册登录信息
    /********************************************/
    /**
     * @writer:曾林
     * @DateTime:2018-01-15
     * @rewriter:杨建
     * @rewriter_date:2018-01-17
     * @description:食材供应商登录接口
     * @param: tel：手机号 || pwd:密码 || code:验证码 || type:APP/WEB 登录
     * @return[$result]
     */
    public function login(){
        $type     = input('type');
        $tel      = input('tel');
        $password = input('pwd');
        // $str      = input('code');
        $str = "zyq878hj25jk8kdjj55jkal55j4kaskdj";
        if(empty($password)&& empty($str) || empty($tel)){
            $result = Config::get('code.miss');
            return json($result);
        }
        if($password){
            $where['password'] = md5($password);
        }
        if($str){
            // $where['password'] = $password;
            //$code = Session::get($tel);
        }
        $where['account'] = $tel;
        $Re = Db::name('supplier')->where($where)->find();
        $Res = Db::name('system_setting')->select();
        if($Re){
                //Cookie::set('user',$Re,30*24*60*60);
                $setstr = getRndString(9);
                $token = md5($setstr);
                $arr = [];
                if($type == 'APP'){
                    $arr = array('app_token' =>$token);
                }
                if($type == 'WEB'){
                    $arr = array('web_token' =>$token);
                }
                //添加token
                db('supplier')->where($where)->update($arr);
                $Ret = Db::name('supplier')->where($where)->find();
                $result = Config::get('code.success');      
                $result['info'] = $Ret;
                $result['setting'] = $Res;
                $noticeRead = Db::table('notice_read')->where(['type'=>1,'status'=>'read'])->count();
                $result['noticeRead'] = $noticeRead;
        }else{
            $result = Config::get('code.logfail');
            $result['info'] = '';
        }
        return json($result);
    }


    /**
     * @writer:yangjian
     * @DateTime:2018-01-27T15:58:40+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商注册接口
     * @param:
     * @return[type] [description]
     */
    public function register(){
        $post = request()->post();
        $pwd = $post['pwd'];
        $tel = $post['tel'];
        if(empty($pwd) || empty($tel)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $Re  = Db::name('supplier')->where('account',$tel)->find();
        $Res = Db::name('user')->where('account',$tel)->find();
        if($Re||$Res){
            $result = Config::get('code.regin');
            return json($result);
        }
        $arr['password'] = md5($pwd);
        $arr['account'] = $tel;
        $arr['tel'] = $tel;
        $arr['send_time_type'] = 1;
        $arr['app_token'] = randomNum();
        $Res = Db::name('supplier')
                ->insert($arr);   
        if($Res){
            $result = Config::get('code.success');
            $result['tel']  = $tel;
            $result['app_token']  = $arr['app_token'];
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-01-27T15:58:25+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:完善供应商信息
     * @param:
     */
    public function setSupplierInfo(){
        $post = request()->post();
        $arr['name']            = $post['company'];
        $arr['company']         = $post['company'];
        $arr['manager']         = $post['manager'] ;
        $arr['tel']             = $post['tel'];
        $arr['manager_tel']     = $post['manager_tel'];
        $arr['post_code']       = $post['post_code'] ;
        $arr['company_code']    = $post['company_code'];
        $arr['address']         = $post['address'];
        $arr['admin_name1']     = $post['admin_name1'];
        $arr['admin_name2']     = $post['admin_name2'];
        $arr['admin_name3']     = $post['admin_name3'];
        $arr['check_status']    = 1;
        $Res = validate('Rules')->scene('setSupplierInfo')->check($arr);//验证字段
        if(!$Res){
            $result = Config::get('code.mistake');
            return json($result);
        }
        $where['account'] = $post['manager_tel'];
        $Re = Db::name('supplier')->where($where)->update($arr);
        if($Re!==false){
            $Re = Db::name('supplier')
                ->alias('A')
                ->field('A.*,S.name as disName,S.id as dis_id,B.message')
                ->join('discount S', 'S.supplier_id = A.id','left')
                ->join('supplier_auth B', 'B.supplier_id = A.id','left')
                ->where('A.account',$post['manager_tel'])
                ->order('dis_id desc')
                ->find();
            $info['supplier_id'] = $Re['id'];
            Db::table('supplier_browse')->insert($info);
            $result = Config::get('code.success');
            $result['info'] =$Re;
            $noticeRead = Db::table('notice_read')->where(['type'=>1,'status'=>'read'])->count();
            $result['noticeRead'] = $noticeRead;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-01-27T17:03:15+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:密码重置
     * @param:
     * @return [type] [description]
     */
    public function resetPassword(){
        $post = request()->post();
        $tel = $post['tel'];
        $pwd = $post['pwd'];
//        $password = md5(input('pwd'));
//        $new_password = md5(input('new_pwd'));
        if(empty($pwd)){
            $result = Config::get('code.missargument');
            return json($result);
        }
        $data['password'] = md5($pwd);
        $Re = Db::name('supplier')->where('account',$tel)->update($data);
        if($Re!==false){
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-01-27T17:15:47+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:
     * @param:重置注册手机号
     * @return [type] [description]
     */
    public function resetTel(){
        $post = request()->post();
        $id = $post['supplier_id'];
        $tel = $post['tel'];
        
        if(empty($tel)){
            $result = Config::get('code.missargument');
            return json($result);
        }
        $Re = Db::name('supplier')->where('tel',$tel)->find();
        if($Re){
            $result = Config::get('code.telIsReg');
            return json($result);
        }
        $data['tel'] = $tel;
        $data['account'] = $tel;
        $Re = Db::name('supplier')->where('id',$id)->update($data);
        if($Re){
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }


    /**
     * @writer:yangjian
     * @DateTime:2018-01-31T10:02:43+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:修改供应商店铺信息
     * @param:
     * @return[type] [description]
     */
    public function shopUpdate(){
        $post = request()->post();
        $arr  = [];
        $id                         = $post['supplier_id'];
        $arr['name']                = $post['name'];
        $arr['image']               = $post['img'];
        $arr['manager_tel']         = $post['tel'];
        $arr['manager_tel2']        = $post['tel2'];
        $arr['manager_tel3']        = $post['tel3'];
        $arr['business']            = $post['business'];
        $arr['shop_introduction']   = $post['shop_introduction'];
        $arr['minimum']             = $post['minimum'];
        $Re = Db::table('supplier')->where('id',$id)->update($arr);
        if($Re!==false){
            $result = Config::get('code.success');
            $noticeRead = Db::table('notice_read')->where(['type'=>1,'status'=>'read'])->count();
            $result['noticeRead'] = $noticeRead;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);

    }
    /********************************************/
    //订单信息
    /********************************************/

    /**
     * @writer:yangjian
     * @DateTime:2018-01-12T13:57:54+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:获取订单列表
     * @param: supplier_id:商户ID || status：订单状态
     */
    public function getOrderList(){
        $post = request()->post();
        // $id   = $post['id'];
        $supplier_id  = $post['supplier_id'];
        $total = input('total', 10, 'intval'); //每页显示数
        $where = [];
        //$whereOr = [];
        $where['a.supplier_id']  = $supplier_id;
        //时间初始值
        $start = '1970-10-1';
        $end = '2030-10-1';
        $status = $post['status'];
        if($status){
            if ($status == 4){
                $where['a.status'] = array('in','3,4');
            }else{
                $where['a.status'] = $status;//状态搜索
            }
            /*if($status=='OVER'){
                $where['a.status'] = array('in','3,4,5,6');
            }*/
        }
        if(input('name')){
            //$where['c.company_name'] = array('like',input('name').'%');//公司名搜索
            $where['c.company_name'] = array('like',input('name').'%');//公司名搜索
        }
        if(input('address')){
            $where['c.addr'] = array('like',input('address').'%');//公司地址搜索
            //$where['c.addr_english'] = array('like',input('address').'%');//公司地址搜索
            //$whereOr['_logic'] = 'or';
        }
        if(input('startTime')){
            $start = input('startTime');//开始时间
        }
        if(input('endTime')){
            $end = input('endTime');//最后时间
            $end = strtotime($end)+24*60*60;
            $end = date("Y-m-d H:i:s",$end);
        }
        if(7==input('day')){
            $start = date('Y-m-d', strtotime('-7 days'));//最近7天搜索
            $end = date('Y-m-d');
        }
        if(30==input('day')){
            $start = date('Y-m-d', strtotime('-300 days'));//最近30天搜索
            $end = date('Y-m-d');
        }
        if(input('category')){
            $map['d.category_id'] = array('in',input('category'));//品种搜索
        }
        if(input('kind')){
            $map['d.type_id'] = array('in',input('kind'));//种类搜索
        }
        if(input('smallType')){
            $map['d.small_type_id'] = array('in',input('smallType'));//品类搜索
        }
        if(input('brand')){
            $map['d.brand_id'] = array('in',input('brand'));//品牌搜索
        }
        if(input('priceMax')){
            $where['a.money'] = array('between',[input('priceMin'),input('priceMax')]);//价格区间接口
        }
        $Re = Db::table('order')
                ->alias('a')
                ->order('add_time desc')
                ->field('a.id,a.order_no,a.user_id,a.status,c.company_name,a.add_time,c.tel,a.id,a.addr,a.addr_english,c.country,c.city,c.town,c.addr as user_addr,DATE_FORMAT(a.add_time,"%m.%d") as day ')
                ->join("user c", "a.user_id = c.id", 'left')
                ->group('a.id')
                ->where($where)
                ->whereTime('add_time', 'between', [$start, $end])
                ->paginate($total,false,['path'=>'javascript:AjaxPage([PAGE])']);
        $count = count($Re);
        $idArr = [];
        for ($i=0; $i < $count; $i++) { 
            array_push($idArr,$Re[$i]['id']);
        }
        $map['b.order_id'] = array('in',$idArr);
        $orderList = Db::name('order_info')
                    ->alias('b')
                    ->field('b.id,b.order_id,b.product_id,b.price,b.num,b.price*b.num as total,b.specification_name,b.packing_proportion,b.unit,d.image,d.name')
                    ->join("product d", "b.product_id = d.id", 'left')
                    ->where($map)
                    ->select();
        if ($orderList){
            foreach ($orderList as $k=>$v){
                $orderList[$k]['price'] = number_format($v['price'],2,'.','');
                $orderList[$k]['total'] = number_format($v['total'],2,'.','');
            }
        }
        if($Re){
            $result = Config::get('code.success');
            $result['count'] = $Re->toArray()['total'];
            $result['list']  = $Re->toArray()['data'];
            foreach($result['list'] as $key => $item){
                $image = Db::name('order_info')->alias('a')
                    ->join("product d", "a.product_id = d.id", 'left')
                    ->where(['order_id'=>$item['id']])
                    ->value('d.image');
                $result['list'][$key]['product_image'] = $image;
            };
            $result['where']            = $where;
            $result['orderList']        = $orderList;
            $result['orderListCount']   = count($orderList);
            $result['maxPage']          = $Re->toArray()['last_page'];
        }else{
            $result = Config::get('code.null');
            $result['list'] = '';
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-04-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:获取订单列表
     * @param: supplier_id:商户ID || status：订单状态
     */
    public function getOrder(){
        $post = Request::instance()->post();
        if (!empty($post['typed']) && !empty($post['supplier_id'])) {
            if ($post['typed'] == 1) {                 //待确认订单(1)
                $where = ['O.supplier_id' => $post['supplier_id'], 'O.status' => 1];
            } elseif ($post['typed'] == 2) {           //我的订单(2)
                $where = ['O.supplier_id' => $post['supplier_id'], 'O.status' => 2];
            } elseif ($post['typed'] == 5) {           //查询订单(已完成5)
                $where = ['O.supplier_id' => $post['supplier_id']];
            } elseif ($post['typed'] == 6) {           //查询订单(已取消6)
                $where = ['O.supplier_id' => $post['supplier_id'], 'O.status' => 6];
            }
            if ($post['typed'] == 5 || $post['typed'] == 6){
                $order = $this->orderInfo($post['supplier_id'], $post['typed']);
                if ($order) {
                    $result = Config::get('code.success');
                    $result['order'] = $order['data'];
                    $result['count'] = $order['count'];
                } else {
                    $result = Config::get('code.null');
                }
                return json($result);
            }
            $date = date("Y-m-d-W", time());
            $date = explode('-', $date);
            for ($i = 0; $i < 4; $i++) {
                $week = date("Y-W", mktime(0, 0, 0, $date[1], $date[2] + $i * 7, $date[0]));
                $week = explode('-', $week);
                $time[] = $this->weekday($week[0], $week[1]);
            }
            //清除本周之前的订单 全部取消掉.
            $old_order = Db::table('order')->where(['supplier_id'=>$post['supplier_id'],'status'=>1])->whereTime('send_time', '<', $time[0][0])->select();
            if ($old_order){
                foreach ($old_order as $k=>$v){
                    Db::table('order')->where('id',$v['id'])->setField('status',6);
                }
            }
            $order = [];
            foreach ($time as $k=>$v){
                reset($v);
                $start_time = current($v);
                $end_time   = end($v);
                $start_date = explode('-', $start_time);
                $end_date   = explode('-', $end_time);
                $start_time = date("Y-m-d", mktime(0, 0, 0, $start_date[1], $start_date[2] - 1, $start_date[0]));
                $end_time   = date("Y-m-d", mktime(0, 0, 0, $end_date[1], $end_date[2] + 1, $end_date[0]));
                $count      = 0;
                if ($post['typed'] == 5) {
                    $data = Db::table('order')
                        ->alias('O')
                        ->field('O.id as order_id, O.money, O.paymoney, O.addr, O.is_user_comment, O.is_supplier_comment,O.is_complaints, O.user_id,
                        S.id as supplier_id, S.name as supplier_name, S.image, S.tel, ifNull(sum(Oi.tax),0) as tax')
                        ->join('order_info Oi', 'Oi.order_id = O.id')
                        ->join('supplier S', 'S.id = O.supplier_id')
                        ->where($where)
                        ->where('O.status', ['=', 3], ['=', 4], 'or')
                        ->whereTime('O.send_time', '>', $start_time)
                        ->whereTime('O.send_time', '<', $end_time)
                        ->order('O.add_time desc')
                        ->group('O.id')
                        ->select();
                } else {
                    $data = Db::table('order')
                        ->alias('O')
                        ->field('O.id as order_id, O.money, O.paymoney, O.status, O.addr, O.is_user_comment, O.is_supplier_comment,O.is_complaints, O.user_id,
                        S.id as supplier_id, S.name as supplier_name, S.image, S.tel, ifNull(sum(Oi.tax),0) as tax')
                        ->join('order_info Oi', 'Oi.order_id = O.id')
                        ->join('supplier S', 'S.id = O.supplier_id')
                        ->where($where)
                        ->whereTime('O.send_time', '>', $start_time)
                        ->whereTime('O.send_time', '<', $end_time)
                        ->order('O.add_time desc')
                        ->group('O.id')
                        ->select();
                }
                if ($data) {
                    $count += count($data);
                    foreach ($data as $kk => $vv) {
                        $data[$kk]['tax'] = number_format($vv['tax'], 2, '.', '');
                        $product['list'] = Db::table('order')
                            ->alias('O')
                            ->field('P.name as product_name, P.image, Oi.product_id, Oi.price, Oi.specification_name, O.send_time,
                            Oi.packing_proportion, P.is_include_tax,Oi.price * Oi.num as total_price,Oi.tax,Oi.num,Oi.unit')
                            ->join('order_info Oi', 'Oi.order_id = O.id')
                            ->join('product P', 'P.id = Oi.product_id')
                            ->where(['O.id' => $vv['order_id']])
                            ->select();
                        $product['count']        = count($product['list']);
                        foreach ($product['list'] as $kkk => $vvv) {
                            $product['list'][$kkk]['price']         = number_format($vvv['price'], 2, '.', '');
                            $product['list'][$kkk]['total_price']   = number_format($vvv['total_price'], 2, '.', '');
                            if ($product['list'][$kkk]['is_include_tax'] == 1) {
                                $product['list'][$kkk]['tax']       = number_format($vvv['tax'], 2, '.', '');
                            } else {
                                $product['list'][$kkk]['tax']       = '--';
                            }
							if($kkk>=2){
								unset($product['list'][$kkk]);
							}	
                        }
                        $data[$kk]['product']    = $product;
                    }
                }
                $start = date("m.d",strtotime($start_time));
                $end   = date("m.d",strtotime($end_time));
                $time  =  $start.'-'.$end;
                if ($k == 0){
                    $order['本周'] = $data;
                }elseif ($k == 1){
                    $order['下周'] = $data;
                }else{
                    $order[$time]  = $data;
                }
            }
            if ($order) {
                $result = Config::get('code.success');
                $result['order'] = $order;
                $result['count'] = $count;
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    public function myDealOrder()
    {
        $post = Request::instance()->post();
        if (!empty($post['supplier_id'])) {
            $where = ['O.supplier_id' => $post['supplier_id'], 'O.status' => 1];
            $date = date("Y-m-d-W", time());
            $date = explode('-', $date);
            for ($i = 0; $i < 4; $i++) {
                $week = date("Y-W", mktime(0, 0, 0, $date[1], $date[2] + $i * 7, $date[0]));
                $week = explode('-', $week);
                $time[] = $this->weekday($week[0], $week[1]);
            }
            $count      = 0;
            foreach ($time as $k=>$v){
                reset($v);
                $start_time = current($v);
                $end_time   = end($v);
                $start_date = explode('-', $start_time);
                $end_date   = explode('-', $end_time);
                $start_time = date("Y-m-d", mktime(0, 0, 0, $start_date[1], $start_date[2] - 1, $start_date[0]));
                $end_time   = date("Y-m-d", mktime(0, 0, 0, $end_date[1], $end_date[2] + 1, $end_date[0]));
                $data = Db::table('order')
                    ->alias('O')
                    ->join('order_info Oi', 'Oi.order_id = O.id')
                    ->join('supplier S', 'S.id = O.supplier_id')
                    ->where($where)
                    ->whereTime('O.send_time', '>', $start_time)
                    ->whereTime('O.send_time', '<', $end_time)
                    ->order('O.add_time desc')
                    ->group('O.id')
                    ->count();
                if ($data) {
                    $count += $data;
                }
            }
            $result = Config::get('code.success');
            $result['count'] = $count;
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    //订单操作
    public function getOrderSet(){
        $post         = request()->post();
        $supplier_id  = $post['supplier_id'];
        $order_id     = $post['order_id'];
        $where = [];
        $where['a.supplier_id']  = $supplier_id;
        $where['a.id']           = $order_id;
        $orderList = Db::table('order')
            ->alias('a')
            ->order('add_time desc')
            ->field('a.*,c.company_name,c.tel,c.name as user_name,c.tel as user_tel,c.country,c.city,c.town,c.addr as user_addr,DATE_FORMAT(a.add_time,"%m.%d") as day ,DATE_FORMAT(a.send_time,"%Y-%m-%d") as send_time ')
            ->join("user c", "a.user_id = c.id", 'left')
            ->where($where)
            ->find();
        $map['b.order_id'] = $order_id;
        $productList = Db::name('order_info')
            ->alias('b')
            ->field('b.id,b.order_id,b.product_id,b.price,b.num,b.price*b.num as total,b.specification_name,b.packing_proportion,b.unit,d.image,d.name')
            ->join("product d", "b.product_id = d.id", 'left')
            ->where($map)
            ->select();
        foreach ($productList as $k=>$v){
            $productList[$k]['price'] = number_format($v['price'], 2, '.', '');
            $productList[$k]['total'] = number_format($v['total'], 2, '.', '');
        }
        $result['orderList']    = $orderList;
        $result['productList']  = $productList;
        return json($result);
    }
    public function getOrderListWeb(){
        $post = input();//request()->post();
        // $id   = $post['id'];
        $supplier_id  = $post['supplier_id'];
        $total = input('total', 10, 'intval'); //每页显示数
        $where = [];
        //$whereOr = [];
        $where['a.supplier_id']  = $supplier_id;
        //时间初始值
        $start = '1970-10-1';
        $end = '2030-10-1';
        $status = $post['status'];
        if($status){
            $where['a.status'] = $status;//状态搜索
            if($status==3){
                $where['a.status'] = array('in','3,4,5');
            }
            if($status==5){
                $where['a.status'] = array('in','5,7');
            }
        }
        if(input('name')){
            //$where['c.company_name'] = array('like',input('name').'%');//公司名搜索
            $where['c.company_name'] = array('like',input('name').'%');//公司名搜索
        }
        if(input('address')){
            $where['c.addr'] = array('like',input('address').'%');//公司地址搜索
            //$where['c.addr_english'] = array('like',input('address').'%');//公司地址搜索
            //$whereOr['_logic'] = 'or';
        }
        if(input('startTime')){
            $start = input('startTime');//开始时间
        }
        if(input('endTime')){
            $end = input('endTime');//最后时间
            $end = strtotime($end)+24*60*60;
            $end = date("Y-m-d H:i:s",$end);
        }
        if(7==input('day')){
            $start = date('Y-m-d', strtotime('-7 days'));//最近7天搜索
            $end = date('Y-m-d');
        }
        if(30==input('day')){
            $start = date('Y-m-d', strtotime('-30 days'));//最近30天搜索
            $end = date('Y-m-d');
        }
        if(input('category')){
            $map['d.category_id'] = array('in',input('category'));//品种搜索
        }
        if(input('kind')){
            $map['d.type_id'] = array('in',input('kind'));//种类搜索
        }
        if(input('smallType')){
            $map['d.small_type_id'] = array('in',input('smallType'));//品类搜索
        }
        if(input('brand')){
            $map['d.brand_id'] = array('in',input('brand'));//品牌搜索
        }
        if(input('priceMax')){
            $where['a.money'] = array('between',[input('priceMin'),input('priceMax')]);//价格区间接口
        }
        $Re = Db::table('order')
            ->alias('a')
            ->order('add_time desc')
            ->field('a.id,a.order_no,a.user_id,a.status,c.company_name,a.add_time,c.tel,a.id,a.addr,a.addr_english,c.country,c.city,c.town,c.addr as user_addr')
            ->join("user c", "a.user_id = c.id", 'left')
            ->group('a.id')
            ->where($where)
            ->whereTime('add_time', 'between', [$start, $end])
            ->select();
        $count = count($Re);
        $idArr = [];
        for ($i=0; $i < $count; $i++) {
            array_push($idArr,$Re[$i]['id']);
        }
        $map['b.order_id'] = array('in',$idArr);
        $orderList = Db::name('order_info')
            ->alias('b')
            ->order('e.add_time desc')
            ->field('b.id,b.order_id,b.product_id,b.price,b.num,b.price*b.num as total,b.specification_name,b.packing_proportion,b.unit,d.image as product_image,d.name,e.*')
            ->join("product d", "b.product_id = d.id", 'left')
            ->join("order e", "b.order_id = e.id", 'left')
            ->where($map)
            ->group('b.order_id')
            ->paginate($total,false,['path'=>'javascript:AjaxPage([PAGE])']);
        //print_r($orderList->toArray()['data']);
        /*if ($orderList){
            foreach ($orderList->toArray()['data'] as $k=>$v){
                $orderList[$k]['price'] = number_format($v['price'],2,'.','');
                $orderList[$k]['total'] = number_format($v['total'],2,'.','');
            }
        }*/
        if($Re){
            $result = Config::get('code.success');
            $result['count'] = $orderList->toArray()['total'];
            $result['list']  = $orderList->toArray()['data'];
            foreach($result['list'] as $key => $item){
                $user_id = Db::name('order')->where(['id'=>$item['order_id']])->value('user_id');
                $user_name = Db::name('user')->where(['id'=>$user_id])->value('company_name');
                $user_tel = Db::name('user')->where(['id'=>$user_id])->value('tel');
                $result['list'][$key]['company_name'] = $user_name;
                $result['list'][$key]['tel'] = $user_tel;
            };
            $result['where']  = $where;
            /*$result['orderList']  = $orderList;
            $result['orderListCount']  = count($orderList);*/
            $result['maxPage']  = $orderList->toArray()['last_page'];
        }else{
            $result = Config::get('code.null');
            $result['list'] = '';
        }
        return json($result);
    }
    /**
     * @writer:yangjian
     * @DateTime:2018-01-12T13:59:48+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:获取订单详情
     * @param: order_id:订单ID
     * @return [type] [description]
     */
    public function getOrderInfo(){
        $post = request()->post();
        $id   = $post['id'];
        $sid  = $post['supplier_id'];
        if(empty($id)||empty($sid)){
            $result = Config::get('code.missargument');
            return json($result);
        }
        $where['a.supplier_id'] = $sid;
        $wha['a.id'] = $id;
        $Re = Db::name('order')
                ->alias('a')
                ->field('a.id,a.user_id,a.order_no,a.money,a.tax,a.addr,a.addr_english,c.country,c.city,c.town,c.addr,c.postcode,c.name,c.tel')
                ->join("user c", "a.user_id = c.id", 'left')
                ->where($wha)
                ->find();
        $Re['money'] = number_format($Re['money'],2,'.','');
        $Re['tax']   = number_format($Re['tax'],2,'.','');
        $whe['b.order_id'] = $id;
        $Res = Db::name('order_info')
                ->alias('b')
                ->field('b.product_id,b.price,b.num,b.price*b.num as total,b.specification_name,b.packing_proportion,b.unit,b.num,b.tax,d.image,d.name,d.status,d.is_shelves,d.image')
                ->join("product d", "b.product_id = d.id", 'left')
                ->where($whe)
                ->select();
        if ($Res){
            foreach ($Res as $k=>$v){
                $Res[$k]['price']  = number_format($v['price'],2,'.','');
                $Res[$k]['total']  = number_format($v['total'],2,'.','');
                $Res[$k]['tax']    = number_format($v['tax'],2,'.','');
            }
        }
        if($Re&&$Res){
            $result = Config::get('code.success');
            $result['info'] = $Re;
            $result['count'] = count($Res);
            $result['list'] = $Res;
        }else{
            $result = Config::get('code.null');
            $result['list'] = '';
        }
        return json($result);
    }


    /**
     * @writer:yangjian
     * @DateTime:2018-01-12T14:01:12+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:修改订单状态接口 【确认、发货、关闭】(可批量修改)
     * @param:status:订单状态 || order_id:订单ID
     * @return[type] [description]
     */
    public function changeOrderStatus(){
        $post   = request()->post();
        $status = $post['tag'];
        $id     = $post['id'];
        $where['o.id'] = array('in',$id);
        if(empty($status)||empty($id)){
            $result = Config::get('code.missargument');
            return json($result);
        }
        $update['status'] = $status;
        $user = Db::name('order')->alias('o')
            ->field('o.*,u.device_id')
            ->join('user u','u.id=o.user_id')
            ->where($where)
            ->select();
        $str = '';
        switch ($post['tag']){
            case 2:
                $str = '商户确认订单';
                break;
            case 3:
                $str = '商户发货';
                break;
            case 6:
                $str = '订单关闭';
                break;
        }
        $time = date('Y-m-d H:i:s');
        $pushArr = [];
        foreach ($user as $item) {
            $data['notice_type']    = 1;
            $data['title']          = $str;
            $data['create_time']    = $time;
            $data['user_id']        = $item['user_id'];
            $data['notice_read_id'] = $item['id'];
            $data['show_type']      = 1;
            Db::name('notice')->insert($data);
            $notice_id = Db::table('notice')->getLastInsID();
            $info = [];
            $info['user_id']    = $item['user_id'];
            $info['status']     = 'nul';
            $info['type']       = 0;
            $info['notice_id']  = $notice_id;
            Db::table('notice_read')->insert($info);
            if($item['device_id']){
                $pushArr[] = $item['device_id'];
            }
        }
        $client = new Jpush('user');
        $client->pushAlias($str,$pushArr);
        $Re = Db::name('order')->alias('o')
            ->where($where)
            ->update(['o.status'=>$status]);
        if ($post['tag'] == 3){
            $Re = Db::name('order')->alias('o')
                ->where($where)
                ->update(['o.delivery_time'=>$time]);
        }elseif ($post['tag'] == 6){
            $Re = Db::name('order')->alias('o')
                ->where($where)
                ->update(['o.delete_time'=>$time]);
        }
        if($Re!==false){
            $result = Config::get('code.success');
            if($post['tag'] == 3){
                $result['difStockAlert'] =  self::subProductStock($id);//减库存
            }
            if($post['tag']==6){
                $result['addStockAlert'] = self::addProductStock($id);//加库存
            }
        }else{
            $result = Config::get('code.editerror');
        }
        return json($result);
    }
    /**
     * @description:web端修改订单状态接口 【确认、发货、关闭】(可批量修改)
     * @param:tag:订单状态 || id:订单ID
     * @return[type] [description]
     */
    public function changeOrderStatusWeb(){
        $post   = request()->post();
        $status = $post['tag'];
        $id     = $post['id'];
        $where['o.id'] = array('in',$id);
        if(empty($status)||empty($id)){
            $result = Config::get('code.missargument');
            return json($result);
        }
        $user = Db::name('order')->alias('o')
            ->field('o.*,u.device_id')
            ->join('user u','u.id=o.user_id')
            ->where($where)
            ->select();
        $str = '';
        switch ($post['tag']){
            case 2:
                $str = '商户确认订单';
                break;
            case 3:
                $str = '商户发货';
                break;
            case 6:
                $str = '订单关闭';
                break;
        }
        $time = date('Y-m-d H:i:s');
        $pushArr = [];
        foreach ($user as $item) {                                 // 消息通知
            $data['notice_type']    = 1;
            $data['title']          = $str;
            $data['create_time']    = $time;
            $data['user_id']        = $item['user_id'];
            $data['notice_read_id'] = $item['id'];
            $data['show_type']      = 1;
            Db::name('notice')->insert($data);
            $notice_id = Db::table('notice')->getLastInsID();
            $info = [];
            $info['user_id']    = $item['user_id'];
            $info['status']     = 'nul';
            $info['type']       = 0;
            $info['notice_id']  = $notice_id;
            Db::table('notice_read')->insert($info);
            $pushArr[] = $item['device_id'];
        }
        $update['o.status'] = $status;
        if(3==$status){
            $update['o.delivery_time'] = date('Y-m-d H:i:s');
        }
        if(6==$status){
            $update['o.delete_time'] = date('Y-m-d H:i:s');
        }
        $Re = Db::name('order')->alias('o')
            ->where($where)
            ->update($update);
        if($Re!==false){
            $result = Config::get('code.success');
            if(3==$status){
                $result['difStockAlert'] =  self::subProductStock($id);//减库存
                // 加销量(不管是否为赠品)
                $addSale = Db::name('order_info')
                    ->where(['order_id'=>$id])
                    ->field('order_id,product_id,SUM(`num` * `packing_proportion`) as sale_num')
                    ->group('product_id')
                    ->select();
                foreach ($addSale as $v){
                    $res = Db::name('product')
                        ->where(['id'=>$v['product_id']])
                        ->setInc('sale_num',$v['sale_num']);
                    if (!$res){
                        $result = Config::get('code.editerror');
                    }
                }
            }
            if(6==$status){
                $result['addStockAlert'] = self::addProductStock($id);//加库存
                // 减销量
                $decSale = Db::name('order_info')
                    ->where(['order_id'=>$id])
                    ->field('order_id,product_id,SUM(`num` * `packing_proportion`) as sale_num')
                    ->group('product_id')
                    ->select();
                foreach ($decSale as $v){
                    $res = Db::name('product')
                        ->where(['id'=>$v['product_id']])
                        ->setDec('sale_num',$v['sale_num']);
                    if (!$res){
                        $result = Config::get('code.editerror');
                    }
                }
            }
        }else{
            $result = Config::get('code.editerror');
        }
        return json($result);
    }

    /********************************************/
    //评论信息
    /********************************************/

    /**
     * @writer:yangjian
     * @DateTime:2018-01-15T15:39:56+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:获取评论列表 商户评论/商品评论
     * @param:product_id：商品ID || supplier_id：商户ID
     * @return [type] [description]
     */
    public function getCommentList(){
        $start  = '1970-10-1';
        $end    = '2030-10-1';
        $supplier_id            = input('supplier_id');
        $order_id               = input('id');
        $where['supplier_id']   = $supplier_id;
        $where['comment_type']   = 0;
        if(empty($supplier_id)){
            $result = Config::get('code.miss');
            return json($result);
        }
        if(3==input('date')){
            $start  = date('Y-m-d', strtotime('-3 days'));//最近3天搜索
            $end    = date('Y-m-d', strtotime('+1 days'));
        }
        if(3==input('score')){
            $where['a.star'] = array('lt',input('score'));//低分搜索
        }
        if(input('category')){
            $where['d.category_id'] = array('in',input('category'));//品种搜索
        }
        if(input('kind')){
            $where['d.type_id'] = array('in',input('kind'));//种类搜索
        }
        if(input('smallType')){
            $where['d.small_type_id'] = array('in',input('smallType'));//品类搜索
        }
        if(input('brand')){
            $where['d.brand_id'] = array('in',input('brand'));//品牌搜索
        }
        if($order_id){
            $where['order_id'] = $order_id;
        }
        $Re = Db::name('comment')->alias('a')
            ->join("user c", "a.user_id = c.id", 'left')
            ->join("product d", "a.product_id = d.id", 'left')
            ->where($where)
            ->whereTime('a.time', 'between', [$start, $end])
            ->field('a.comment,a.time,c.name,c.addr,a.star,a.id')
            ->order('a.time desc')
            ->paginate(10,false,['path'=>'javascript:AjaxPage([PAGE])']);
        if($Re){
            $result = Config::get('code.success');
            $result['count'] = $Re->toArray()['total'];
            $result['list']  = $Re->toArray()['data'];
            $result['where']  = $where;
            $result['maxPage']  = $Re->toArray()['last_page'];
        }else{
            $result = Config::get('code.null');
            $result['list'] = '';
        }
        return json($result);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-01-15T15:43:50+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:评论详情
     * @param: id:评论id
     * @return[type] [description]
     */
    public function commentInfo(){
        $post = request()->post();
        $id = $post['orderId'];
        if(empty($id)){
            $result = Config::get('code.missargument');
            return json($result);
        }
        $Re = Db::name('comment_to_supplier')
                ->field('a.*,b.comment as supplier_comment,b.star as supplier_star')
                ->alias('a')
                ->join('comment b', 'a.order_id = b.order_id', 'left')
                ->group('')
                ->where('a.order_id',$id)
                ->find();
        if($Re){
            $result = Config::get('code.success');
            $result['info'] = $Re;
        }else{
            $result = Config::get('code.error');
            $result['info'] = '';
        }
        return json($result);  
    }


    /**
     * @writer:yangjian
     * @DateTime:2018-01-15T15:45:41+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:评论添加
     * @param:order_id:订单ID || supplier_id：供应商ID || star:星级 || comment:评论内容 || user_id:用户ID || product_id:商品ID
     */
    public function addComment(){
        $post = input();//request()->post();
        $id = $post['order_id'];
        if (empty($id)) {
            $result = Config::get('code.missargument');
            return json($result);
        }
        unset($post['type']);
        unset($post['token']);
        $post['time']           = date('Y-m-d H:i:s', time());
        $post['comment_type']   = 1;
        $Res = Db::name('comment')->where(['order_id'=>$id,'user_id'=>$post['user_id']])->find();
        if (!$Res) {
            $Re = Db::name('comment')->insert($post);
        } else {
            $Re = Db::name('comment')->where(['order_id'=>$id,'user_id'=>$post['user_id']])->update($post);
        }
        Db::table('order')->where('id',$id)->setField('is_supplier_comment',1);
        if ($Re !== false) {
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }


    /***********************************************************/
    //配送信息管理  每个商家生成31条数据 每天一条配送信息
    /***********************************************************/


    /**
     * @writer:yangjian
     * @DateTime:2018-01-16T17:17:06+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:设置配送地址
     * @param: type:类型 月/星期 || sign:标签(判断删除原始配送时间依据 1删除全部 2删除当天day数据) 
     * @param: supplier_id：供应商ID || send_area：配送地址 || area_id：配送地址ID || send_area_english：英文配送地址 || day：配送日期
     */
    public function setAddr(){
        $post = request()->post();
        $tag  = $post['tag'];
        $day  = $post['day'];
        $sign = $post['sign'];
        $id   = $post['supplier_id'];
        if(empty($id)|| empty($tag)|| empty($day)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $area  = $post['send_area'];
        // $enames= []; 
        $names = [];
        if($area){
            $names  = explode(',',$post['send_area']);
            // $enames = explode(',',$post['send_area_english']);
        }
        Db::startTrans();
        try{
            //判断是否全部删除 配送信息 sign 为1全删除 2删除当天day数据
            $delwhere['supplier_id']    = $id;
            $update['send_time_type']   = $tag;
            $add['supplier_id']         = $id;
            if($tag==1){
                Db::name('supplier_send_manage')
                    ->where($delwhere)
                    ->where('month','<>','0')
                    ->delete();
            }
            if($tag==2){
                $delwhere1['month'] = 0;
                $delwhere['day']    = $day;
                $delwhere['month']  = $post['month'];
                $add['month']       = $post['month'];
                Db::name('supplier_send_manage')
                    ->where($delwhere)
                    ->whereOr($delwhere1)
                    ->delete();
            }
            foreach ($names as $key => $value) {
                $add['day']= $day;
                $add['send_area']  = $names[$key];
                if ($tag==1){
                    Db::table('supplier_send_manage')->where(['day'=>$day,'send_area'=>$add['send_area']])->delete();
                }
                if ($tag==2){
                    Db::table('supplier_send_manage')->where(['day'=>$day,'month'=>$add['month'],'send_area'=>$add['send_area']])->delete();
                }
                // $add['send_area_english']  = $enames[$key];
                Db::name('supplier_send_manage')->insert($add);
            }
            Db::table('supplier')->where('id',$id)->update($update);
            $result = Config::get('code.success');
            Db::commit();    
        } catch (\Exception $e) {
            Db::rollback();
            $result = Config::get('code.editerror');
        }
        return json($result);  
    }
    
    /**
     * 商户web端增加配送地址
     * @return array
     */
    public function addSendAddress(){
        $data = input('request.');
        $exsit = Db::name('supplier_send_manage')->where($data)->count();
        if($exsit){
            $res = config('code.error');
            $res['msg'] = '已经添加过的区域';
        }else{
            $ok = Db::name('supplier_send_manage')->insertGetId($data);
            $res = $ok ? config('code.success') : config('code.error');
        }
        /*if(!validate('Supplier')->scene('add_address')->check($data)){
            $res = config('code.error');
            $res['msg'] = validate('Supplier')->getError();
        }else{
            $exsit = Db::name('supplier_send_manage')->where($data)->count();
            if($exsit){
                $res = config('code.error');
                $res['msg'] = '已经添加过的地址';
            }else{
                $ok = Db::name('supplier_send_manage')->insertGetId($data);
                $res = $ok ? config('code.success') : config('code.error');
            }
        }*/
        return $res;
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-01-16T17:27:08+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:删除配送地址
     * @param: 
     * @param: 
     */
    function delAddr(){
        $post = request()->post();
        $tag = $post['tag'];
        $day  = $post['day'];
        $sign = $post['sign'];
        $id   = $post['supplier_id'];
        if(empty($id)|| empty($tag)|| empty($day)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $delwhere['send_area'] = $post['name'];
        $delwhere['day'] = $day;
        $delwhere['supplier_id'] = $id;
        $delwhere['month'] = $post['month'];
        $Res = Db::name('supplier_send_manage')
            ->where($delwhere)
            ->delete();
        if ($Res !== false) {
            $result = Config::get('code.delsuccess');
        } else {
            $result = Config::get('code.error');
        }
        $result['where'] = $delwhere;
        return json($result);  
       
    }
    
    function delAllAddressBySupplierIdDay(){
        try {
            $data = input('request.');
            if(!validate('Supplier')->scene('del_address')->check($data)){
                $res = config('code.error');
                $res['msg'] = validate('Supplier')->getError();
            }else{
//                $first = Db::name('supplier_send_manage')->where($data)->find();
//                if ($first !== true){
//                    $res['msg'] = '暂无配送区域，请先添加!';
//                    return json($res);
//                }
//                $ok = Db::name('supplier_send_manage')
//                    ->where($data)
//                    ->setField('send_area','');
                $ok = Db::name('supplier_send_manage')->where($data)->delete();
                $res = $ok ? config('code.success') : config('code.error');
            }
        } catch (\Exception $ex) {
            $res = config('code.lose');
        }
        return json($res);
    }

    /**
     * @writer:yangjian
     * @DateTime:2018-02-05T14:18:01+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:获取配送地址信息 
     * @param: tag：配送类型（ 1周 / 2月）
     * @param: day：tag为1标识星期几  为2时为几号
     * @return[type] [description]
     */
    public function getSendAddr(){
        $post = request()->post();
        $id   = $post['supplier_id'];
        if(empty($id)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $tag = $post['tag'];
        $where['month'] = $post['month'];
        // if($tag==2){
        //     $where['month'] = $post['month'];
        // }
        // if($tag==1){
        //     $where['month'] = 0;
        // }
        if(!empty($post['day'])){
            $where['day'] = $post['day'];
        }
        $where['supplier_id'] = $id;
        $Re = Db::name('supplier_send_manage')
                ->where($where)
                ->select();
        if($Re){
            $result = Config::get('code.success');
            $result['list'] = $Re;
            $result['count']= count($Re);
        }else{
            $result = Config::get('code.null');
        }
        return json($result);  
    }


    /********************************************/
    //统计信息
    /********************************************/


    public function statistics(){
        $post = input();
        $id = $post['supplier_id'];
        if(empty($id)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $clickNUm = $orderNum = 0;
        $orderNum = Db::name('order')->where(['supplier_id'=>$id,'status'=>['neq',7]])->count();
        /*$orderNum = Db::name('order')
                    ->where('supplier_id',$id)
                    ->group('user_id')
                    ->order('user_id desc')
                    ->count();*/
        $Re = Db::name('supplier_browse')->where(['supplier_id'=>$id])->select();
        foreach($Re as $key => $item){
            $clickNUm += $item['browse_num'];
        }
        $list = Db::name('order_info')
                    ->alias('a')
                    ->field('b.id,b.name,b.image,sum(a.num * a.packing_proportion) as numa,b.unit')
                    ->join('product b', 'b.id = a.product_id')
                    ->join('order c', 'c.id = a.order_id')
                    ->where('c.supplier_id',$id)
                    ->where(['c.status'=>['neq',7]])
                    ->group('a.product_id')
                    ->order('numa desc')
                    ->select(); 
        $result = Config::get('code.success');
        $result['list'] = $list;
        $result['count'] = count($list);
        $result['orderNum'] = $orderNum;
        $result['clickNUm'] = $clickNUm;
        return json($result);
    }




    /********************************************/
    //意外添加接口
    /********************************************/


    /**
     * @writer:杨建
     * @DateTime:1018-1-26 10:28
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:食材供应商店铺开启/关闭
     * @param:
     * @return [$result]
     */
    public function setSupplierOpen(){
        $post  = request()->post();
        $id    = $post['supplier_id'];
        $status= $post['status'];
        if(empty($id)){
            $result = Config::get('code.miss');
            return json($result);
        }
        $where['id'] = $id;
        $Re = Db::name('supplier')
                ->where($where)
                ->find();
        if($Re){
            if($status == '0'){
                $status = 0;
            }
            if($status == '1'){
                $status = 1;
            }
            //$update['is_open'] = $status;
            $Res = Db::table('supplier')->where($where)->setField('is_open',$status);
            if($Res!==false){
                $result = Config::get('code.success');
                $result['open'] = $status;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }    

    /**
     * @writer:yangjian
     * @DateTime:2018-02-03T16:48:59+0800
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description:新增优惠
     * @param:
     */
    public function addDiscount()
    {
        $post  =  Request::instance()->post();
        if (!array_key_exists('type', $post) || empty($post['type'])){
            return json(Config::get('code.mistake'));
        }
        $post['condition_money'] = $post['price'] * $post['condition_num'];
        $data = [];
        $data['name']                   = $post['name'];
        $data['type']                   = $post['typed'];
        $data['condition_money']        = $post['condition_money'];
        $data['condition_num']          = $post['condition_num'];
        $data['relief_money']           = $post['relief_money'];
        $data['start_time']             = date('Y-m-d H:i:s',strtotime($post['start_time']));
        $data['end_time']               = date('Y-m-d H:i:s',strtotime($post['end_time']));
        $data['add_time']               = date("Y-m-d H:i:s",time());
        $data['supplier_id']            = $post['supplier_id'];
        $data['product_id']             = $post['product_id'];
        $data['give_product']           = $post['give'];
        $data['status']                 = 1;
        $discount  = Db::name('discount')
            ->where(['supplier_id'=>$data['supplier_id'],'product_id'=>$data['product_id'],'status'=>1])
            ->find();
        if ($discount){
            $result = Config::get('code.error');
            $result['msg'] = '该商品已参与其他活动';
            return json($result);
        }else{
            $Re = Db::name('discount')->insert($data);
            if($Re !== false){
                $result = Config::get('code.success');
                $result['info']['name'] = $data['name'];
            }else{
                $result = Config::get('code.null');
            }
            return json($result);
        }
    }
    /*
     * 获取订单id减商品库存
     *
     */
    static private function  subProductStock($id){
        $where['order_id'] = array('in',$id);
        //查询订单详情
        $orderList = Db::name('order_info')->where($where)->select();
        $result = [];
        $difData = [];
        foreach($orderList as $key => $item){
            //查询商品库存
            $productStock = Db::name('product')->where(['id'=>$item['product_id']])->find();
            $number = $item['num']*$item['packing_proportion'];             // 规格乘数量
            if($number > $productStock['stock']){
                $result['diff'] =  Config::get('code.productDif');
                $difData[$key]['product_name'] = $productStock['name'];
                $difData[$key]['product_id'] = $productStock['id'];
                $difData[$key]['product_dif'] = $number - $productStock['stock'];
            }
            else{
                $data = ['stock'=>$productStock['stock'] - $number];
                Db::name('product')->where(['id'=>$item['product_id']])->update($data);
            }
        }
        $result['difStatus'] = 200;
        $result['stock'] = $difData;
        return $result;
    }
    /*
     * 获取订单加商品库存
     * */
    static private function  addProductStock($id){
        $where['order_id'] = array('in',$id);
        //查询订单详情
        $orderList = Db::name('order_info')->alias('a')
            ->field('a.*,b.status')
            ->join('order b', 'b.id = a.order_id')
            ->where($where)
            ->select();
        $result = [];
        foreach($orderList as $key => $item){
            //查询商品库存
            $productStock = Db::name('product')->where(['id'=>$item['product_id']])->find();
            $number = $item['num']*$item['packing_proportion'];             // 规格乘数量
            $data = ['stock'=>$productStock['stock'] + $number];
            if($item['status'] >= 3){
                if(Db::name('product')->where(['id'=>$item['product_id']])->update($data)){
                    $result['addStatus'] = 200;
                }
            }
        }
        return $result;
    }

    // 获取周始末时间
    private function weekday($year, $week)
    {
        $year_start = mktime(0, 0, 0, 1, 1, $year);
        // 判断第一天是否为第一周的开始
        if (intval(date('W', $year_start)) === 1) {
            $start = $year_start;//把第一天做为第一周的开始
        } else {
            $week++;
            $start = strtotime('+1 monday', $year_start);//把第一个周一作为开始
        }
        // 第几周的开始时间
        if ($week === 1) {
            $date['start'] = date("Y-m-d", $start);
        } else {
            $date['start'] = date("Y-m-d", strtotime('+' . ($week - 0) . ' monday', $start));
        }
        $se = [];
        $se[] = $date['start'];
        $start = explode('-', $date['start']);
        for ($i = 1; $i < 7; $i++) {
            $se[] = date("Y-m-d", mktime(0, 0, 0, $start[1], $start[2] + $i, $start[0]));
        }
        return $se;
    }

    // 获取各类订单
    private function orderInfo($supplierId, $type){
        $end_time   = date("Y-m-d", time());
        $date       = explode('-', $end_time);
        $start_time = date("Y-m-d", mktime(0, 0, 0, $date[1], $date[2] - 30, $date[0]));
        $end_time   = date("Y-m-d", mktime(0, 0, 0, $date[1], $date[2] + 1, $date[0]));
        $count      = 0;
        if ($type == 5) {
            $data = Db::table('order')
                ->alias('O')
                ->field('O.id as order_id, O.money, O.paymoney, O.status, O.addr, O.is_user_comment, O.is_supplier_comment,O.is_complaints, O.user_id,
                S.id as supplier_id, S.name as supplier_name, S.image, S.tel, ifNull(sum(Oi.tax),0) as tax')
                ->join('order_info Oi', 'Oi.order_id = O.id')
                ->join('supplier S', 'S.id = O.supplier_id')
                ->where('O.supplier_id',$supplierId)
                ->where('O.status',['=', 3], ['=', 4], 'or')
                ->whereTime('O.add_time', '>', $start_time)
                ->whereTime('O.add_time', '<', $end_time)
                ->order('O.add_time desc')
                ->group('O.id')
                ->select();
        } else {
            $data = Db::table('order')
                ->alias('O')
                ->field('O.id as order_id, O.money, O.paymoney, O.status, O.addr, O.is_user_comment, O.is_supplier_comment,O.is_complaints, O.user_id,
                S.id as supplier_id, S.name as supplier_name, S.image, S.tel, ifNull(sum(Oi.tax),0) as tax')
                ->join('order_info Oi', 'Oi.order_id = O.id')
                ->join('supplier S', 'S.id = O.supplier_id')
                ->where('O.supplier_id',$supplierId)
                ->where('O.status',$type)
                ->whereTime('O.delete_time', '>=', $start_time)
                ->whereTime('O.delete_time', '<=', $end_time)
                ->order('O.add_time desc')
                ->group('O.id')
                ->select();
        }
        if ($data) {
            $count = count($data);
            foreach ($data as $kk => $vv) {
                $data[$kk]['tax'] = number_format($vv['tax'], 2, '.', '');
                $product['list'] = Db::table('order')
                    ->alias('O')
                    ->field('P.name as product_name, P.image, Oi.product_id, Oi.price, Oi.specification_name, O.send_time,
                            Oi.packing_proportion, Oi.unit, P.is_include_tax,Oi.price * Oi.num as total_price,Oi.tax,Oi.num')
                    ->join('order_info Oi', 'Oi.order_id = O.id')
                    ->join('product P', 'P.id = Oi.product_id')
                    ->where(['O.id' => $vv['order_id']])
                    ->select();
                $product['count']        = count($product['list']);
                foreach ($product['list'] as $kkk => $vvv) {
                    $product['list'][$kkk]['price']         = number_format($vvv['price'], 2, '.', '');
                    $product['list'][$kkk]['total_price']   = number_format($vvv['total_price'], 2, '.', '');
                    if ($product['list'][$kkk]['is_include_tax'] == 1) {
                        $product['list'][$kkk]['tax']       = number_format($vvv['tax'], 2, '.', '');
                    } else {
                        $product['list'][$kkk]['tax']       = '--';
                    }
                    if($kkk>=2){
                        unset($product['list'][$kkk]);
                    }
                }
                $data[$kk]['product']    = $product;
            }
        }
        $re['data']  = $data;
        $re['count'] = $count;
        return $re;
    }

    /**
     * 对比验证码
     * @return \think\response\Json
     */
    public function checkCode(){
        $post  = request()->post();
        $tel = $post['tel'];
        $code = $post['code'];
        if (empty($tel)|| empty($code)){
            $result= Config::get('code.miss');
            return json($result);
        }
        $sendCode = Session::get('telCode_'.$tel);
        $sendTime = Session::get($tel.'start');
        if (time()-$sendTime > 300){
            $result= Config::get('code.error');
            $result['msg'] = '验证码过期，请重新获取验证码!';
            return json($result);
        }
        if ($code == $sendCode){
            $result= Config::get('code.success');
            return json($result);
        }else{
            $result= Config::get('code.error');
            $result['msg'] = '验证码错误!';
            return json($result);
        }
    }

}



